define(function(require, exports, module) {
	//lib工具包
	require('resources/js/jquery.json-2.4.min.js');
	require('avalon2');
	
	//公用逻辑
	var resConstants=require('resources/js/rescatalogMix/res_constants.js');
	
	var ResPublishEditor=require('resources/template/resInfo/resPublish_editor.js');
	var resPublishEditorTpl=require('text!resources/template/resInfo/resPublish_editor_tpl.html');
	
	//模块代码
	require('resources/js/GooFlow-0.8/GooFlow.js');
	var FlowChart=require('resources/js/rescatalogMix/FlowChart.js');
	
	var ResPublishOperate=function(params){
		//默认值
		this.curResId=-1;
		this.resInfos={};	//<resId,resInfo>
		this.resInfoCmp={};	//<resId,ResInfoSchemaOperate,ServiceOperatePlugin>
		//配置
		$.extend(true,this,params);
		this.init();
	};
	ResPublishOperate.prototype={
		//初始化
		init:function(){
			//创建渲染
			this.render();
			//事件绑定
			this.bind();
			//状态数据同步
			this.sync();
		},
		render:function(){
			this.$div=$('#res-edit');
			this.resPublishDiv=$('.resPublish-property',this.$div);
			$(resPublishEditorTpl).prependTo(this.resPublishDiv);
			
			//工作流
			this.curTaskNode&&(this.flowChart=new FlowChart({
				dataUrl:this.getUrl('workflow')+this.instanceId,
				id:'workFlow',
				curNodeName:this.curTaskNode
			}));
		},
		bind:function(){
			var that=this;
			this.$div.on('click','.delete-form',function(){
				var resId=$(this).attr('resId');
				delete that.resInfos[resId];
				that.resInfoCmp[resId].destroy();
				delete that.resInfoCmp[resId];
			});
			$('#addSchemaResInfo').on('click',function(){
				that.addSchemaResInfo();
			});
			$('#addServiceResInfo').on('click',function(){
				that.addServiceResInfo();
			});
			$('#btn-save').on('click',function(){
				that.submit('save');
			});
			$('#btn-publish').on('click',function(){
				that.submit(that.data==undefined||that.data[0].code=='100'?'publish':'publish2');
			});
			$('#backWard').on('click',function(){
				jump(that.getUrl('list'),that.listParam);
			});
		},
		sync:function(){
			var that=this;
			if(this.resPublishId==0)
			{
				this.resPublish={
						title:'',
						reason:'',
						appId:'',
						userId:this.userId,
						createTime:new Date().Format('yyyy-MM-dd hh:mm:ss')	
					};
			}
			else
			{
				$.ajax(this.getUrl('load'),{
					data:{resPublishId:this.resPublishId},
					async:false,
					type:'POST',
					dataType:'json'
				}).done(function(data){
					that.resPublish=data;
				}).fail(function(){});
			}	
			this.resPublish.userName=this.userName;
			//主表单填充
			//使用avalon填充
			this.resPublishVM = avalon.define($.extend(true,{
                $id: "resPublishVM",
                step:'draft'
            },this.resPublish));//联合资源的vm
			avalon.scan(this.$div.get(0),this.resPublishVM);
			//初始化 子组件
			this.resPublishEditor=new ResPublishEditor(this.resPublishVM,this.resPublishDiv,this.getCmpConfig());
			this.resPublish.items&&this.resPublish.items.length>0&&
			$.each($.map(this.resPublish.items,function(ele){return ele.resInfo}),function(index,resInfo){
				if(resInfo.resType==1)
					that.addSchemaResInfo(resInfo);
				else if(resInfo.resType==2)
					that.addServiceResInfo(resInfo);
			});
		},
		addSchemaResInfo:function(resInfo){
			var ResInfoSchemaOperate=require('resources/template/resInfo/resInfo_schema_operate.js'),
				resId=this.curResId--,
				$formContainer=$('#formContainer');
			if(resInfo==undefined)
				resInfo={
					resId:resId,
					bizName:'',
					resProviderName:this.org.name,
					resProviderCode:this.org.code,
					resProvider:this.org.id,
					resType:1,
					carrierType:'',	//一定要写上，否则无法实现双向绑定
					resTypeName:resConstants.resType[1],
					schema:{
						schemaId:resId,
						entries:[]
					}	
				};
			this.resInfos[resId]=resInfo
			this.resInfoCmp[resId]=new ResInfoSchemaOperate(resInfo,$formContainer,this.getCmpConfig());
		},
		getCmpConfig:function(){
			return {
				baseUrl:this.baseUrl,
				step:'draft',
				selfDelete:false
			};
		},
		addServiceResInfo:function(resInfo){
			var ServiceOperatePlugin=require('resources/template/resInfo/resInfo_service_editor.js'),
				resId=this.curResId--,
				$formContainer=$('#formContainer');
			if(resInfo==undefined)
				resInfo={
					resId:resId,
					bizName:'',
					resProviderName:this.org.name,
					resProviderCode:this.org.code,
					resProvider:this.org.id,
					resType:2,
					carrierType:'',	//一定要写上，否则无法实现双向绑定
					resTypeName:resConstants.resType[2],
					service:{
						serviceId:resId,
						serviceType:'',
						serviceMemo:''
					}
				};
			this.resInfos[resId]=resInfo
			this.resInfoCmp[resId]=new ServiceOperatePlugin(resInfo,$formContainer,this.getCmpConfig());
		},
		urls:{
			edit:{
				save:'/resPublish/updateSave.jhtml',
				publish:'/resPublish/updatePublish.jhtml',
				publish2:'/resPublish/updatePublish2.jhtml',
				workflow:'/facade/workflowXML.jhtml?instanceId=',
				load:'/resPublish/loadResPublish.jhtml'
			},
			create:{
				save:'/resPublish/createSave.jhtml',
				publish:'/resPublish/createPublish.jhtml',
			},
			list:'/resPublishX/main.jhtml'
		},
		getUrl:function(action){
			if(this.urls[this.operateCode][action])
				return this.baseUrl+this.urls[this.operateCode][action];
			else if(this.urls[action])
				return this.baseUrl+this.urls[action];
			else 
				return this.baseUrl+action;
		},
		getData:function(){
			this.errorCount=0;
			
			//resPublish 数据&错误
			this.resPublish=resPublishOperate.resPublishVM.$model;
			this.resPublishError=this.resPublishEditor.getError();
			this.errorCount+=this.resPublishError.length;
			
			//各个resInfo 数据&错误
			this.resInfoError=[];
			var resInfoCmp,resInfo,resInfoName=[];
			this.resPublish.items=[];
			for(var resId in this.resInfoCmp)
			{
				resInfoCmp=this.resInfoCmp[resId];
				resInfoCmp.getData();
				resInfo=resInfoCmp.resInfo;
				this.errorCount+=resInfoCmp.resInfoError.length;
				this.resInfoError.unshift(resInfoCmp.resInfoError);
				this.resPublish.items.push({
					twId:this.resPublish.resPublishId,
					resId:resInfo.resId,
					resInfo:resInfo
				});
				resInfoName.push(resInfo.bizName);
			}
			var resInfoNameDuplicate=Common.hasDuplicate(resInfoName);
			if(resInfoNameDuplicate.length>0)
				this.resPublishError.push("存在重名的资源:"+resInfoNameDuplicate.join(','));
			if(this.resPublish.items==0)
			{
				this.resPublishError.push("至少申请发布一个资源");
				this.errorCount++;
			}
		},
		validate:function(){
			this.getData();
			if(this.errorCount==0)
				return true;
			//格式化错误信息并弹出提醒框
			var html=[];
			html.push('提交信息存在错误：<br/>');
			if(this.resPublishError.length>0)
			html.push('&nbsp;&nbsp;&nbsp;&nbsp;'+this.resPublishError.join('，<br/>&nbsp;&nbsp;&nbsp;&nbsp;')+".<br/>");
			for(var index=0;index<this.resInfoError.length;index++)
			{
				if(this.resInfoError[index].length==0)
					continue;
				html.push('&nbsp;&nbsp;&nbsp;&nbsp;第'+(index+1)+'个资源表单：<br/>');
				html.push('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
				html.push(this.resInfoError[index].join('，<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')+'。<br/>');
			}
			tipHtml(html.join(''),350);
			return false;
		},
		submit:function(action){
			if(!this.validate())
				return;
			mask.show();
			var that=this,submitData=[this.resPublish];
			if(action=='publish2'||(this.operateCode=='edit'&&action=='publish'))
			{
				submitData[0].resPublishId=this.resPublishId;
				submitData[0].wfVersionId=this.wfVersionId;
				submitData[0].instanceId=this.instanceId;
				submitData[0].taskId=this.taskId;
			}
			$.ajax(this.getUrl(action),{
				headers: {          
					"Accept" : "text/html; charset=utf-8",         
					"Content-Type": 'application/json;charset=utf-8'  
				},
				data:$.toJSON(submitData),
				async:false,
				type:'POST',
				dataType:'json'
			}).done(function(data){
				mask.hide();
				if(data.success){
					window.parent&&window.parent.parent&&window.parent.parent.getNum&&window.parent.parent.getNum();
					jump(that.getUrl('list'),that.listParam);
				}else{
					tip(data.message);
				}
			}).fail(function(){});
		}
	};
	
	
	return ResPublishOperate;
});